package ua.org.extjsbuilder.parser.runtime.data;

import ua.org.extjsbuilder.parser.JSObject;

public class JSBoolean implements JSObject {
	private static final String TRUE_KEYWORD = "true";
	private static final String FALSE_KEYWORD = "false";
	
	public static final JSBoolean TRUE = new JSBoolean(true);
	public static final JSBoolean FALSE = new JSBoolean(false);
	
	private boolean value;
	
	public JSBoolean(boolean value){
		this.value = value;
	}

	@Override
	public boolean equals(Object obj) {
		if(obj==null)return !value;
		if(obj==this)return true;
		if(obj instanceof Boolean){
			return ((Boolean)obj).booleanValue()==value;
		}
		if(obj instanceof JSBoolean){
			return ((JSBoolean)obj).value==value;
		}
		return false;
	}

	@Override
	public int hashCode() {
		return value?1:0;
	}
	
	@Override
	public String toString() {
		return String.valueOf(value);
	}

	public static boolean isBooleanLiteral(CharSequence keyword) {
		if(TRUE_KEYWORD.length()==keyword.length()){
			return match(TRUE_KEYWORD,keyword);
		}
		else if(FALSE_KEYWORD.length()==keyword.length()){
			return match(FALSE_KEYWORD,keyword);
		}
		return false;
	}

	public static JSBoolean parseBoolean(CharSequence keyword) {
		return match(TRUE_KEYWORD,keyword)?TRUE:FALSE;
	}
	
	private static boolean match(CharSequence keyword,CharSequence test){
		int len = keyword.length();
		for(int i=0;i<len;i++){
			if(keyword.charAt(i)!=test.charAt(i))return false;
		}
		return true;
	}
}
